package forum;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;



public class Thread {

 	private int threadID;
	private int subForumID;
	
	private String subForumName;
	
	private String name;
 	private int createdBy;
 	private User creator;
 	private Timestamp createdOn;
	private int views;
 	private int replies;
 	private Post latestPost;
 	private Post[] posts;
 	public Thread(){
 		
 	}
 	
 	
 	public Thread(int threadID, int subForumID,String name,int createdBy, Timestamp createdOn,int views, int replies){
 		this.threadID = threadID;
 		this.subForumID = subForumID;
 		this.views = views;
 		this.replies = replies;
 		this.name = name;
 		this.createdBy = createdBy;
 		this.createdOn = createdOn;
 		
 		this.subForumName = getNameOfSubforum();
 		
 		try{
 			Connection conn = db_code.connect();
			Statement stmt = conn.createStatement();
			ResultSet rs = null;
			
			String query;
			query = "SELECT * FROM user WHERE userID = '" + createdBy + "' LIMIT 1;";
			
			rs = stmt.executeQuery(query);
			
			while(rs.next()){
				this.creator  = new User(
						rs.getInt("userID"),
						rs.getInt("userlvl"),
						rs.getString("name"),
						rs.getString("email"),
						rs.getString("password"),
						rs.getTimestamp("joined"),
						rs.getInt("numberOfPosts")
						);
			}
			db_code.disconnect(conn);
 		}
		catch(SQLException e){
			System.out.println("SQL statement error!");
			e.printStackTrace();
		}
 	}
 	
 	public Thread(int subforumid, String NameOfThread, int userID ) {
 		this.threadID = 0;
 		this.subForumID = subforumid;
 		this.views = 0;
 		this.replies = 0;
 		this.name = NameOfThread;
 		this.createdBy = userID;
 		this.createdOn = new Timestamp(System.currentTimeMillis());
 		
 		this.subForumName = getNameOfSubforum();
 		Connection conn = db_code.connect();
 		try{
 			
			Statement stmt = conn.createStatement();
			ResultSet rs = null;
			
			String query;
			query = "SELECT * FROM user WHERE userID = '" + createdBy + "' LIMIT 1;";
			
			rs = stmt.executeQuery(query);
			
			while(rs.next()){
				this.creator  = new User(
						rs.getInt("userID"),
						rs.getInt("userlvl"),
						rs.getString("name"),
						rs.getString("email"),
						rs.getString("password"),
						rs.getTimestamp("joined"),
						rs.getInt("numberOfPosts")
						);
			}
			db_code.disconnect(conn);
 		}
		catch(SQLException e){
			db_code.disconnect(conn);
			System.out.println("SQL statement error!");
			e.printStackTrace();
		}
	}

	public synchronized void Create(){
 		
		Connection conn =  db_code.connect();
		try {
 			
			Statement stmt =conn.createStatement();
			String query = "INSERT INTO thread (subForumID, name, createdBy, createdOn, views, replies)" +
					"VALUES(" + 
						subForumID + ",'" + 
						name + "'," + 
						createdBy + ",'" + 
						createdOn + "'," + 
						views + "," +
						replies + ");";
			
			stmt.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
			
			ResultSet rs = stmt.getGeneratedKeys();
			
			if ( rs.next() ) {
			    int key = rs.getInt(1);
			    setThreadID(key);
			}
			db_code.disconnect(conn);
		} catch (Exception e) {
			db_code.disconnect(conn);
			System.out.println("FAIL! INSERT!");
			e.printStackTrace();
		}
 	}
 	
 	public synchronized void Edit(){
 		Connection conn =  db_code.connect();
 		try {
 			
			Statement stmt =conn.createStatement();
			String query = "UPDATE thread " +
					"SET " +
						"subForumID = " + subForumID + "," +
						"name = '" + name + "'," +
						"createdBy = " + createdBy +","+
						"createdOn = '" + createdOn + "',"+
						"views = " + views + ","+
						"replies = " + replies +
					"WHERE " +
						"threadID = " + threadID;
			
			stmt.execute(query);
			db_code.disconnect(conn);
		} catch (Exception e) {
			db_code.disconnect(conn);
			System.out.println("FAIL! INSERT!");
			e.printStackTrace();
		}
 		
 	}
 	
 	public synchronized void Delete(){
 		Connection conn =  db_code.connect();
 		try {
 			
			Statement stmt =conn.createStatement();
			
			String query = "DELETE FROM thread WHERE threadID = " + threadID;
			stmt.execute(query);
			
			db_code.disconnect(conn);
			
		} catch (Exception e) {
			db_code.disconnect(conn);
			System.out.println("FAIL! DELETE!");
			e.printStackTrace();
		}
 	}
 	
 	public String getNameOfSubforum(){
 		Connection conn =  db_code.connect();
		try {
			
			Statement stmt =conn.createStatement();
			String query = "SELECT name FROM subforum WHERE subForumID = "+subForumID+" LIMIT 1;";
			
			ResultSet rs = stmt.executeQuery(query);
			
			
			if ( rs.next() ) {
			    String name = rs.getString(1);
			    db_code.disconnect(conn);
			    return name;
			}
			db_code.disconnect(conn);
		} catch (Exception e) {
			db_code.disconnect(conn);
			System.out.println("FAIL! getSubforumName!");
			e.printStackTrace();
		}
		return "";
	}
 	
 	public synchronized void incrementThreadReplies(){
		incrementThread(threadID, true);
		replies++;
	}
	
	public synchronized void incrementThreadViews(){
		incrementThread(threadID, false);
		views++;
	}
	
	private synchronized void incrementThread(int id, boolean replies){
		Connection conn =  db_code.connect();
		try{
			
			Statement stmt =conn.createStatement();
			String query;
			
			if(replies)
				query= "UPDATE thread SET replies=replies+1 WHERE threadID = " + id;
			else
				query= "UPDATE thread SET views=views+1 WHERE threadID = " + id;
			 
			stmt.execute(query);
			db_code.disconnect(conn);
		}
		catch(SQLException e){
			db_code.disconnect(conn);
			System.out.println("SQL statement error!");
			e.printStackTrace();
		}
	}
 	
	public ArrayList<Post> getAllPosts(){
		ArrayList<Post> result = new ArrayList<Post>();
		Connection conn =  db_code.connect();
		try{
			
			Statement stmt = conn.createStatement();
			ResultSet rs = null;
			
			String query = "SELECT * FROM post WHERE threadID = " + threadID;
			
			rs = stmt.executeQuery(query);
			
			Post row;
			while(rs.next()){
				row  = new Post(
						(Integer)rs.getObject("postID"), 
						(Integer)rs.getObject("threadID"), 
						(Integer)rs.getObject("userID"), 
						(String)rs.getObject("content"), 
						(Timestamp)rs.getObject("createdOn"), 
						(Timestamp)rs.getObject("lasteditedOn"));
				result.add(row);
			}
			db_code.disconnect(conn);
			return result;
		}
		catch(SQLException e){
			db_code.disconnect(conn);
			System.out.println("SQL statement error!");
			e.printStackTrace();
			return null;
		}
	}
	
 	public String toString(){
		return "threadID: " + threadID + 
				", subForumID: " + subForumID + 
				", name: "  + name + 
				", createdBy: " + createdBy +
				", createdOn: " + createdOn +
				", views: "  + views + 
				", replies: "  + replies;
	}
 	
 	public int getThreadID() {
		return threadID;
	}
	public void setThreadID(int threadID) {
		this.threadID = threadID;
	}
	public int getSubForumID() {
		return subForumID;
	}
	public void setSubForumID(int subForumID) {
		this.subForumID = subForumID;
	}
	public String getName() {
		if(name == null || name.equals("")){
			Connection conn = db_code.connect();
			try{
	 			
				Statement stmt = conn.createStatement();
				ResultSet rs = null;
				
				String query;
				query = "SELECT * FROM thread WHERE threadID = '" + this.threadID + "' LIMIT 1;";
				
				rs = stmt.executeQuery(query);
				rs.next();
				this.name = rs.getString("name");
				
				db_code.disconnect(conn);
	 		}
			catch(SQLException e){
				db_code.disconnect(conn);
				System.out.println("SQL statement error!");
				e.printStackTrace();
			}
		}
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getCreatedBy() {
		return createdBy;
	}
	public void setCreatedBy(int createdBy) {
		this.createdBy = createdBy;
	}
	public Timestamp getCreatedOn() {
		return createdOn;
	}
	public void setCreatedOn(Timestamp createdOn) {
		this.createdOn = createdOn;
	}
	public int getViews() {
		Connection conn = db_code.connect();
		try{
 			
			Statement stmt = conn.createStatement();
			ResultSet rs = null;
			
			String query;
			query = "SELECT views FROM thread WHERE threadID = '" + this.threadID + "' LIMIT 1;";
			
			rs = stmt.executeQuery(query);
			rs.next();
			this.views = rs.getInt("views");
			
			db_code.disconnect(conn);
 		}
		catch(SQLException e){
			db_code.disconnect(conn);
			System.out.println("SQL statement error!");
			e.printStackTrace();
		}

		return views;
	}
	public void setViews(int views) {
		this.views = views;
		Connection conn =  db_code.connect();
		try{
			
			Statement stmt =conn.createStatement();
			String query;
			query= "UPDATE thread SET views=" + views + " WHERE threadID = " + this.threadID;
			stmt.execute(query);
			db_code.disconnect(conn);
		}
		catch(SQLException e){
			db_code.disconnect(conn);
			System.out.println("SQL statement error!");
			e.printStackTrace();
		}
		
	}
	public int getReplies() {
		return replies;
	}
	public void setReplies(int replies) {
		this.replies = replies;
	}


	public Post getLatestPost() {
		Connection conn = db_code.connect();
		try{
 			
			Statement stmt = conn.createStatement();
			ResultSet rs = null;
			
			String query;
			query = "SELECT * FROM post WHERE threadID = '" + this.threadID + "' ORDER BY createdOn DESC LIMIT 1;";
			
			rs = stmt.executeQuery(query);
			
			while(rs.next()){
				this.latestPost  = new Post(
						rs.getInt("postID"),
						rs.getInt("threadID"),
						rs.getInt("userID"),
						rs.getString("content"),
						rs.getTimestamp("createdOn"),
						rs.getTimestamp("lasteditedOn")
						);
			}
			db_code.disconnect(conn);
 		}
		catch(SQLException e){
			db_code.disconnect(conn);
			System.out.println("SQL statement error!");
			e.printStackTrace();
		}
		return latestPost;
	}


	public void setLatestPost(Post latestPost) {
		this.latestPost = latestPost;
	}


	public User getCreator() {
		return creator;
	}


	public void setCreator(User creator) {
		this.creator = creator;
	}


	public Post[] getPosts() {
		Connection conn = db_code.connect();
		try{
 			
			Statement stmt = conn.createStatement();
			ResultSet rs = null;
			
			String query;
			query = "SELECT * FROM post WHERE threadID = '" + this.threadID + "' ORDER BY createdOn;";
			
			rs = stmt.executeQuery(query);
			ArrayList<Post> tmp = new ArrayList<Post>();
			while(rs.next()){
				tmp.add(new Post(
						rs.getInt("postID"),
						rs.getInt("threadID"),
						rs.getInt("userID"),
						rs.getString("content"),
						rs.getTimestamp("createdOn"),
						rs.getTimestamp("lasteditedOn")
						));
			}
			db_code.disconnect(conn);
			this.posts = new Post[tmp.size()];
			for(int i = 0;i<tmp.size();i++){
				posts[i]=tmp.get(i);
			}
 		}
		catch(SQLException e){
			db_code.disconnect(conn);
			System.out.println("SQL statement error!");
			e.printStackTrace();
		}
		
		return posts;
	}


	public void setPosts(Post[] posts) {
		this.posts = posts;
	}


	public String getSubForumName() {
		return subForumName;
	}


	public void setSubForumName(String subForumName) {
		this.subForumName = subForumName;
	}

}
